import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { authApi } from '@/api'
import type { User, LoginRequest, Permission } from '@/types'
import Cookies from 'js-cookie'
import request from '@/utils/request'
import { PermissionUtils } from '@/constants/permissions'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string>(Cookies.get('token') || '')
  const user = ref<User | null>(null)
  const permissions = ref<Permission[]>([])

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const hasPermission = computed(() => (permission: string) => {
    const userPermissionCodes = permissions.value.map(p => p.code)
    return PermissionUtils.hasPermission(userPermissionCodes, permission)
  })

  // 新增权限验证方法
  const hasAnyPermission = computed(() => (requiredPermissions: string[]) => {
    const userPermissionCodes = permissions.value.map(p => p.code)
    return PermissionUtils.hasAnyPermission(userPermissionCodes, requiredPermissions)
  })

  const hasAllPermissions = computed(() => (requiredPermissions: string[]) => {
    const userPermissionCodes = permissions.value.map(p => p.code)
    return PermissionUtils.hasAllPermissions(userPermissionCodes, requiredPermissions)
  })

  // 获取权限分组
  const getPermissionsByModule = computed(() => (module: string) => {
    const userPermissionCodes = permissions.value.map(p => p.code)
    return PermissionUtils.getPermissionsByModule(module as any)
  })

  // 获取权限名称
  const getPermissionName = computed(() => (permission: string) => {
    return PermissionUtils.getPermissionName(permission)
  })

  // 获取权限描述
  const getPermissionDescription = computed(() => (permission: string) => {
    return PermissionUtils.getPermissionDescription(permission)
  })

  // 登录
  const login = async (loginData: LoginRequest) => {
    try {
      const response = await authApi.login(loginData)
      const { token: newToken, user: userData } = response.data
      
      token.value = newToken
      user.value = userData
      
      // 保存token到cookie
      Cookies.set('token', newToken, { expires: 7 })
      
      // 获取用户权限
      await getUserPermissions()
      
      return response
    } catch (error) {
      throw error
    }
  }

  // 登出
  const logout = async () => {
    try {
      await authApi.logout()
    } catch (error) {
      console.error('登出失败:', error)
    } finally {
      // 清除状态
      token.value = ''
      user.value = null
      permissions.value = []
      
      // 清除cookie
      Cookies.remove('token')
    }
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const response = await authApi.getProfile()
      user.value = response.data;
      
      // 获取用户权限
      await getUserPermissions()
      
      return response
    } catch (error) {
      throw error
    }
  }

  // 获取用户权限
  const getUserPermissions = async () => {
    try {      
      // 从用户信息中获取权限
      if (user.value && user.value.permissions) {
        // 如果用户信息中已经有权限数组，直接使用
        const permissionCodes = user.value.permissions        
        const allPermissions: Permission[] = permissionCodes.map(code => ({
          id: 0, // 临时ID，实际使用时可能需要从后端获取完整权限信息
          name: PermissionUtils.getPermissionName(code),
          code: code,
          description: PermissionUtils.getPermissionDescription(code),
          module: PermissionUtils.getPermissionModule(code),
          action: PermissionUtils.parsePermissionCode(code)?.action || code,
          createdAt: '',
          updatedAt: ''
        }))
        permissions.value = allPermissions
        
      } else if (user.value && user.value.userRoles) {
        // 从用户角色中提取权限（备用方案）
        const allPermissions: Permission[] = []
        user.value.userRoles.forEach(userRole => {
          if (userRole.role && userRole.role.rolePermissions) {
            userRole.role.rolePermissions.forEach(rolePermission => {
              if (rolePermission.permission) {
                allPermissions.push(rolePermission.permission)
              }
            })
          }
        })
        permissions.value = allPermissions
      } else {
        permissions.value = []
      }
      
      
    } catch (error) {
      console.error('获取权限失败:', error)
      permissions.value = []
    }
  }

  // 刷新token
  const refreshToken = async () => {
    try {
      const response = await authApi.refreshToken()
      const newToken = response.data.token
      
      token.value = newToken
      Cookies.set('token', newToken, { expires: 7 })
      
      return response
    } catch (error) {
      throw error
    }
  }

  // 修改密码
  const changePassword = async (oldPassword: string, newPassword: string) => {
    try {
      const response = await request.post('/auth/change-password', {
        oldPassword,
        newPassword
      })
      return response
    } catch (error) {
      throw error
    }
  }

  return {
    // 状态
    token,
    user,
    permissions,
    
    // 计算属性
    isLoggedIn,
    hasPermission,
    hasAnyPermission,
    hasAllPermissions,
    getPermissionsByModule,
    getPermissionName,
    getPermissionDescription,
    
    // 方法
    login,
    logout,
    getUserInfo,
    getUserPermissions,
    refreshToken,
    changePassword
  }
}) 